from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from django.db.models import Q, Count
from movies.models import (
    FilmDetails,
    TagOption,
    FilmGenre
)
from accounts.models import (
    UserAccount
)


def movies_search(request):
    user_info = request.session.get('info', {})
    user_id = user_info.get('id')
    if user_id:
        try:
            user_account = UserAccount.objects.get(id=user_id)
            username = user_account.username
        except UserAccount.DoesNotExist:
            pass
    # 获取所有不同的标签类别
    categories = TagOption.objects.values_list(
        'category', flat=True).distinct()
    context = {
        'categories': categories,
        'user_id': user_id,
        'username': username
    }
    return render(request, 'movies_search.html', context)


def get_tag_options(request):
    # 从请求中获取类别
    category = request.GET.get('category')

    # 根据类别查询对应的标签选项
    if category:
        options = TagOption.objects.filter(
            category=category).values('id', 'value')
    else:
        options = TagOption.objects.none()

    # 返回JSON响应
    return JsonResponse({'tag_options': list(options)})


def movies_results(request):
    user_info = request.session.get('info', {})
    user_id = user_info.get('id')
    if user_id:
        try:
            user_account = UserAccount.objects.get(id=user_id)
            username = user_account.username
        except UserAccount.DoesNotExist:
            pass
    # 获取搜索参数
    key = request.GET.get("s", "")
    movie_type = request.GET.get("type", "")
    tag_values = request.GET.getlist("tags")  # 获取标签文本值列表
    page = int(request.GET.get("page", 1))
    limit = int(request.GET.get("limit", 20))

    if movie_type == 'new':
        movie_search_rs = FilmDetails.objects.order_by("-pubdate")
    elif movie_type == 'top':
        movie_search_rs = FilmDetails.objects.order_by("-rating")
    elif movie_type == 'tag' and tag_values:
        # 通过TagOption的value过滤FilmDetails，并计算匹配的标签数量
        movie_search_rs = FilmDetails.objects.filter(
            filmtags__tag_name__in=TagOption.objects.filter(
                value__in=tag_values).values_list('value', flat=True)
        ).annotate(
            matching_tags=Count('filmtags')
        ).order_by('-matching_tags', '-pubdate').distinct()
    else:
        # 根据电影标题搜索
        query = Q(title__icontains=key) | Q(original_title__icontains=key)
        movie_search_rs = FilmDetails.objects.filter(query)

    # 实现分页
    total_movies = movie_search_rs.count()
    start = (page - 1) * limit
    end = start + limit
    paged_movies = movie_search_rs[start:end]

    # 构建响应数据
    context = {
        'movies': paged_movies,
        'key': key,
        'type': movie_type,
        'tags': tag_values,
        'page': page,
        'total_pages': (total_movies + limit - 1) // limit,
        'user_id': user_id,
        'username': username
    }
    return render(request, 'movies_results.html', context)


def movies_details(request, movie_id):
    user_info = request.session.get('info', {})
    user_id = user_info.get('id')
    if user_id:
        try:
            user_account = UserAccount.objects.get(id=user_id)
            username = user_account.username
        except UserAccount.DoesNotExist:
            pass
    movie = get_object_or_404(FilmDetails, movie_id=movie_id)

    # 将电影对象传递给模板
    context = {
        'movie': movie,
        'user_id': user_id,
        'username': username
    }
    return render(request, 'movies_details.html', context)


def recommend_for_user(request, user_id):
    if user_id:
        try:
            user_account = UserAccount.objects.get(id=user_id)
            username = user_account.username
        except UserAccount.DoesNotExist:
            username = None

    # 定义 movie_ids
    movie_ids = ["3541415", "1307914","1292722" ]

    # 按照 movie_ids 的顺序获取电影详细信息
    movies = [FilmDetails.objects.get(movie_id=movie_id) for movie_id in movie_ids]

    movie_genres = FilmGenre.objects.all()
    tag_options = TagOption.objects.all()
    tag_values = {}
    for option in tag_options:
        if option.category not in tag_values:
            tag_values[option.category] = []
        tag_values[option.category].append(option.value)

    context = {
        'movies': movies,
        'type': movie_genres,
        'tags': tag_values,
        'user_id': user_id,
        'username': username
    }
    return render(request, 'movies_recommend.html', context)

